package ar.com.android.restoapp.utils;

import java.text.SimpleDateFormat;
import java.util.ArrayList;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONObject;

import android.content.Context;
import android.util.Log;
import ar.com.android.restoapp.dbHelpers.SQLFoodOrderHelper;
import ar.com.android.restoapp.entities.Food;
import ar.com.android.restoapp.entities.Order;
import ar.com.android.restoapp.entities.OrderItems;
import ar.com.android.restoapp.entities.Tables;
import ar.com.android.restoapp.entities.TypeFood;
import ar.com.android.restoapp.http.CustomHttpClient;
import ar.com.android.restoapp.providers.FoodProvider;
import ar.com.android.restoapp.providers.OrderItemDataSource;
import ar.com.android.restoapp.providers.OrderProvider;
import ar.com.android.restoapp.providers.TablesProvider;
import ar.com.android.restoapp.providers.TypeFoodProvider;

public class SyncDatabase {
	
	private static final String TAG = "SyncDatabase";
	
	public static Tables syncDatabaseTableStatus(Context context, Integer idTable) throws Exception 
	{
		try 
		{
			TablesProvider tablesDataSource = new TablesProvider(context);
			
			Tables table = tablesDataSource.getTable(idTable);
			
			if(table != null && table.getState().equals(Constants.TABLE_CLOSE)) {
			
				ArrayList<NameValuePair> postParameters;
				String response;
				
				//Tables Sync
				postParameters = new ArrayList<NameValuePair>();
				postParameters.add(new BasicNameValuePair(Constants.ACTION, Constants.ACTION_GETTABLE_STATE));
				postParameters.add(new BasicNameValuePair(Constants.PARAM_IDTABLE, idTable.toString()));
			
				response = CustomHttpClient.executeHttpPost(Constants.URL_SERVER_UTILS, postParameters);
				JSONObject joTable = new JSONObject(response);
				
				table.setState(joTable.getString("state"));
				tablesDataSource.updateTable(table);
			}
			return table;
		}
		catch (Exception e) {
			Log.e(TAG, "Error UPDATE state Table.\n" + e);
			throw new Exception("Error UPDATE state Table.\n" + e);
		}
	}
	
	public static void syncDatabaseFood(Context context) throws Exception
	{
		SQLFoodOrderHelper sqlHelper = SQLFoodOrderHelper.getHelper(context);
		sqlHelper.dbOpen();
		sqlHelper.beginTransaction();
		
		TypeFoodProvider typeFoodDataSource = new TypeFoodProvider(context);
		FoodProvider foodDataSource = new FoodProvider(context);
		TablesProvider tablesDataSource = new TablesProvider(context);
		OrderProvider orderDataSource = new OrderProvider(context);
		OrderItemDataSource orderItemDataSource = new OrderItemDataSource(context);
		
		ArrayList<NameValuePair> postParameters;
		String response;
		
		try 
		{
			//TypeFood Sync
			postParameters = new ArrayList<NameValuePair>();
			postParameters.add(new BasicNameValuePair(Constants.ACTION, Constants.ACTION_GETTYPEFOOD));
			postParameters.add(new BasicNameValuePair(Constants.PARAM_IDRESTAURANT, AppGlobalVariables.getInstance().getIdRestaurant().toString()));
		
			response = CustomHttpClient.executeHttpPost(Constants.URL_SERVER_UTILS, postParameters);
			JSONArray jaTypeFoods = new JSONArray(response);
			
			typeFoodDataSource.removeTypeFood();
			for(int iLoop = 0; iLoop < jaTypeFoods.length(); iLoop++)
			{
				JSONObject joTypeFood = jaTypeFoods.getJSONObject(iLoop);
				
				TypeFood typeFood = new TypeFood();
				typeFood.setIdTypeFood(joTypeFood.getInt("idTypeFood"));
				typeFood.setTypeDescription(joTypeFood.getString("typeDescription"));
				typeFood.setIdMenuFood(joTypeFood.getInt("idMenuFood"));
				
				typeFoodDataSource.insertTypeFood(typeFood);
			}
			
			//typeFoodDataSource.dbClose();
			
			//Food Sync
			postParameters = new ArrayList<NameValuePair>();
			postParameters.add(new BasicNameValuePair(Constants.ACTION, Constants.ACTION_GETFOOD));
			postParameters.add(new BasicNameValuePair(Constants.PARAM_IDRESTAURANT, AppGlobalVariables.getInstance().getIdRestaurant().toString()));
		
			response = CustomHttpClient.executeHttpPost(Constants.URL_SERVER_UTILS, postParameters);
			JSONArray jaFoods = new JSONArray(response);
			
			foodDataSource.removeFood();
			for(int iLoop = 0; iLoop < jaFoods.length(); iLoop++)
			{
				JSONObject joFood = jaFoods.getJSONObject(iLoop);
				
				Food food = new Food();
				food.setIdFood(joFood.getInt("idFood"));
				food.setDescription(joFood.getString("description"));
				food.setIdTypeFood(joFood.getInt("idTypeFood"));
				food.setPrice(joFood.getDouble("price"));
				
				foodDataSource.insertFood(food);				
			}
						
			//Tables Sync
			postParameters = new ArrayList<NameValuePair>();
			postParameters.add(new BasicNameValuePair(Constants.ACTION, Constants.ACTION_GETTABLES));
			postParameters.add(new BasicNameValuePair(Constants.PARAM_IDUSER, AppGlobalVariables.getInstance().getIdUser().toString()));
			postParameters.add(new BasicNameValuePair(Constants.PARAM_IDRESTAURANT, AppGlobalVariables.getInstance().getIdRestaurant().toString()));
		
			response = CustomHttpClient.executeHttpPost(Constants.URL_SERVER_UTILS, postParameters);
			JSONArray jaTables = new JSONArray(response);
			
			tablesDataSource.removeTables();
			for(int iLoop = 0; iLoop < jaTables.length(); iLoop++)
			{
				JSONObject joTable = jaTables.getJSONObject(iLoop);
				
				Tables table = new Tables();
				table.setIdTable(joTable.getInt("idTable"));
				table.setDescription(joTable.getString("description"));
				table.setState(joTable.getString("state"));
				table.setQuantityGuest(0);
				
				tablesDataSource.insertTable(table);
			}
			
			//Order Sync
			postParameters = new ArrayList<NameValuePair>();
			postParameters.add(new BasicNameValuePair(Constants.ACTION, Constants.ACTION_GETORDER));
			postParameters.add(new BasicNameValuePair(Constants.PARAM_IDRESTAURANT, AppGlobalVariables.getInstance().getIdRestaurant().toString()));
			
			response = CustomHttpClient.executeHttpPost(Constants.URL_SERVER_UTILS, postParameters);
			JSONArray jaOrder = new JSONArray(response);
			
			SimpleDateFormat sdf = new SimpleDateFormat(Constants.FORMAT_ANDROID_DATETIME);
			
			orderDataSource.removeOrder();
			orderItemDataSource.removeOrderItem();
			
			if(!jaOrder.getJSONObject(0).getString("status").equals("EOF"))
			{	
				for(int iLoop = 0; iLoop < jaOrder.length(); iLoop++)
				{
					JSONObject joOrder = jaOrder.getJSONObject(iLoop);
					Order order = new Order();
					order.setIdOrder(joOrder.getInt("idOrderFood"));
					order.setIdTable(joOrder.getInt("idTable"));
					order.setNumGuest(joOrder.getInt("numGuests"));
					order.setState(joOrder.getString("state"));
					order.setDateFrom(sdf.parse(joOrder.getString("dateFrom")));
					order.setDateTo(sdf.parse(joOrder.getString("dateTo")));
					
					Tables table = tablesDataSource.getTable(order.getIdTable());
					if(table!=null)
					{
						table.setState(order.getState());
						table.setQuantityGuest(order.getNumGuest());
						tablesDataSource.updateTable(table);
					}
					
					orderDataSource.insertOrder(order);
					
					JSONArray jaOrderItem = new JSONArray(joOrder.getString("items"));
					
					for(int jLoop = 0; jLoop < jaOrderItem.length(); jLoop++)
					{
						JSONObject joOrderItem = jaOrderItem.getJSONObject(jLoop);
						OrderItems orderItem = new OrderItems();
						
						orderItem.setOrderItemId(joOrderItem.getInt("idOrderFoodItem"));
						orderItem.setIdFood(joOrderItem.getInt("idFood"));
						orderItem.setIdTable(order.getIdTable());
						
						Food food = foodDataSource.getFood(orderItem.getIdFood());
						
						orderItem.setOrderDescription(food.getDescription());
						orderItem.setOrderQuantity(joOrderItem.getDouble("quantity"));
						orderItem.setPrice(joOrderItem.getDouble("price"));
						orderItem.setState(joOrderItem.getString("state"));
						orderItem.setSelected(false);
						
						orderItemDataSource.insertFood(orderItem);
					}
				}				
			}
			
			sqlHelper.commitTransaction();
			sqlHelper.dbClose();

		} catch (Exception e) {
			sqlHelper.rollbackTransaction();
			Log.e(TAG, "Error while sync Database.\n" + e);
			throw new Exception("Error while sync Database.\n" + e);
		}
		
	}
}
